package com.zhugang.week04;

/**
 * @program algorithms
 * @description: insertionSortList
 * @author: chanzhugang
 * @create: 2022/06/18 08:35
 */
public class InsertionSortList {

    /**
     * 147. 对链表进行插入排序
     *
     * @param head
     * @return
     */
    public ListNode insertionSortList(ListNode head) {
        // 已经排好序的节点
        ListNode dummyHead = new ListNode(Integer.MIN_VALUE, null);
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            ListNode q = dummyHead;
            // 遍历查找插入位置（核心逻辑）
            while (q.next != null && q.next.val <= p.val) {
                // p节点的前置节点：q.next.val > p.val
                q = q.next;
            }
            // 将p节点插入在q节点后
            p.next = q.next;
            q.next = p;
            p = temp;
        }
        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}